import Axios from 'axios'
import { Message } from 'element-ui'

const http = (router, store) => {
  const instance = Axios.create({
    // baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:5000' : 'http://rubbsh.aiyund.top',
    baseURL: 'http://api.aiyund.top',
    timeout: 15000
  })

  instance.interceptors.request.use(config => {
    if(store.state.token) {
      config.headers['Authorization'] = 'Bearer ' + store.state.token
    }
    
    return config
  }, err => {
    return Promise.reject(err)
  })

  instance.interceptors.response.use(res => {
    if(res.data.code !== 0) {
      Message({
        message: res.data.message || 'Error!',
        type: 'error',
        duration: 5000
      })
    }
    return res.data
  }, error => {
    if(error.response.status === 401) {
      Message({
        message: error.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      router.push('/login')
    }

    if(error.response.status.toString().startsWith('50')) {
      Message({
        message: error.response.data.msg || 'Error',
        type: 'error',
        duration: 3000
      })
    }
    return Promise.reject(error)
  })

  return instance
}

export default http;